﻿import os
import uuid
from flask import Flask, render_template, request, redirect, session,request,jsonify
from werkzeug.utils import secure_filename

app = Flask(__name__)
# 设置会话密钥，用于会话管理
app.secret_key = 'your_secret_key'
app.config['IMAGE_UPLOAD_FOLDER'] = 'uploads/images'  # 图片上传目录
app.config['ALLOWED_IMAGE_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
app.config['VIDEO_UPLOAD_FOLDER'] = 'uploads/videos'  # 视频上传目录
app.config['ALLOWED_VIDEO_EXTENSIONS'] = {'mp4', 'avi', 'mov', 'mkv'}

# 模拟用户数据库
users = {
    'admin': '123456',
    'user1':'123456'
}

posts=[
        {
            "id":1,
            "title":"第一篇博客文章",
            "content": "这是第一篇博客文章的内容。",
            "author": "user1"
        },
        {
            "id": 2,
            "title": "第二篇博客文章",
            "content": "这是第二篇博客文章的内容。",
            "author": "user1"
        },
        {
            "id": 3,
            "title": "第三篇博客文章",
            "content": "这是第二篇博客文章的内容。",
            "author": "user1"
        },
        {
            "id": 4,
            "title": "第二篇博客文章",
            "content": "这是第二篇博客文章的内容。",
            "author": "user1"
        },
        {
            "id": 5,
            "title": "第二篇博客文章",
            "content": "这是第二篇博客文章的内容。",
            "author": "user1"
        },
        {
            "id": 6,
            "title": "第二篇博客文章",
            "content": "这是第二篇博客文章的内容。",
            "author": "user1"
        },
        {
            "id": 7,
            "title": "第二篇博客文章",
            "content": "这是第二篇博客文章的内容。",
            "author": "user1"
        }
    ]

@app.route('/')
def index():
    # 检查用户是否已登录
    if 'username' in session:
        return render_template('index.html', username=session['username'],posts=posts)
    return redirect('/login')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # 验证用户输入的用户名和密码
        if username in users and users[username] == password:
            # 登录成功，将用户名存入会话
            session['username'] = username
            return redirect('/')
        else:
            return '用户名或密码错误'
    return render_template('login.html')

@app.route('/logout')
def logout():
    # 清除会话中的用户名，实现退出登录
    session.pop('username', None)
    return redirect('/login')

@app.route('/post/<int:post_id>')
def post(post_id):
    post = next((p for p in posts if p["id"] == post_id), None)
    if post:
        return render_template('post.html', post=post)
    return "文章未找到", 404

@app.route('/admin')
def admin_index():
    # 检查用户是否已登录
    if 'username' in session:
        return render_template('admin_index.html', username=session['username'],posts=posts)
    return redirect('/admin/login')

@app.route('/admin/login', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # 验证用户输入的用户名和密码
        if username in users and users[username] == password:
            # 登录成功，将用户名存入会话
            session['username'] = username
            return redirect('/admin')
        else:
            return '用户名或密码错误'
    return render_template('admin_login.html')

@app.route('/add')
def add():
	return render_template('add.html')

@app.route('/admin/content/add',methods=['POST'])
def add_content():
    # 获取文章标题
    title = request.form.get('title', '')  # request.form 用于获取表单数据
    # 获取关键字
    keywords = request.form.get('keywords', '') 
    # 获取文章内容（HTML 格式）
    content = request.form.get('content', '') 
    # 保存到数据库（假设有一个数据库模型，如 SQLAlchemy）
    # Article(title=title, keywords=keywords, content=content).save()
    # 返回响应
    return jsonify({
        'success': True,
        'message': '文章发布成功！'
    })

def allowed_file(filename, allowed_extensions):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions

@app.route('/upload/image', methods=['POST'])
def upload_image():
    # 检查是否有文件上传
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    # 检查文件名是否为空
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    # 检查文件类型是否允许
    if not allowed_file(file.filename, app.config['ALLOWED_IMAGE_EXTENSIONS']):
        return jsonify({'error': 'File type not allowed'}), 400
    # 生成唯一的文件名
    unique_filename = f"{str(uuid.uuid4())}.{file.filename.rsplit('.', 1)[1].lower()}"
    save_path = os.path.join(app.config['IMAGE_UPLOAD_FOLDER'], unique_filename)
    # 保存文件
    file.save(save_path)
    # 返回图片的 URL
    return jsonify({
        'success': True,
        'url': f"/uploads/images/{unique_filename}"  # 根据你的服务器配置调整 URL
    })

@app.route('/upload/video', methods=['POST'])
def upload_video():
    # 检查是否有文件上传
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    # 检查文件名是否为空
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    # 检查文件类型是否允许
    if not allowed_file(file.filename, app.config['ALLOWED_VIDEO_EXTENSIONS']):
        return jsonify({'error': 'File type not allowed'}), 400
    # 生成唯一的文件名
    unique_filename = f"{str(uuid.uuid4())}.{file.filename.rsplit('.', 1)[1].lower()}"
    save_path = os.path.join(app.config['VIDEO_UPLOAD_FOLDER'], unique_filename)
    # 保存文件
    file.save(save_path)
    # 返回视频的 URL
    return jsonify({
        'success': True,
        'url': f"/uploads/videos/{unique_filename}"  # 根据你的服务器配置调整 URL
    })

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0',port=8080)
